//
// Created by liushuai on 2021/2/7.
//

#include "reverseBetween.h"
ListNode *reverseBetween(ListNode *head, int m, int n) {
    if (!head)
        return head;
    ListNode *currentNode = head;
    ListNode *endNode = head;
    ListNode *finalNode = head;
    ListNode *preNode = nullptr;
    for (int i = 1; i < m; i++) {
        preNode = currentNode;
        currentNode = currentNode->next;
        endNode = endNode->next;
    }
    for (int i = 0; i < n - m; i++)
        endNode = endNode->next;
    if (endNode) {
        finalNode = endNode->next;
        endNode->next = nullptr;
    }
    ListNode *revseredTail = reverseLinklist(currentNode);
    if (preNode) {
        preNode->next = revseredTail;
    }
    if (finalNode)
        currentNode->next = finalNode;
    if (!preNode)
        return revseredTail;
    else
        return head;
}
